<template>
  <div class="password-reset">
    <div class="page-header">
      <h2>密码重置管理</h2>
      <p>管理员可以在此生成用户的密码重置令牌</p>
    </div>
    
    <el-card class="reset-card">
      <div class="reset-form">
        <el-form
          ref="resetFormRef"
          :model="resetFormData"
          :rules="rules"
          label-width="100px"
          @submit.prevent="generateToken"
        >
          <el-form-item label="用户名" prop="username">
            <el-input 
              v-model="resetFormData.username"
              placeholder="请输入需要重置密码的用户名"
              clearable
            />
          </el-form-item>
          
          <el-form-item>
            <el-button 
              type="primary" 
              :loading="loading" 
              @click="generateToken"
            >
              生成重置令牌
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-divider content-position="center">令牌信息</el-divider>
      
      <div class="token-info" v-if="tokenInfo">
        <el-alert
          type="success"
          :title="`用户 ${tokenInfo.username} 的重置令牌已生成`"
          :closable="false"
          show-icon
        />
        
        <div class="token-details">
          <div class="token-item">
            <span class="token-label">重置令牌:</span>
            <el-tag type="danger" size="large">{{ tokenInfo.token }}</el-tag>
            <el-button 
              type="primary" 
              size="small" 
              icon="el-icon-document-copy" 
              circle
              @click="copyToClipboard(tokenInfo.token)"
            ></el-button>
          </div>
          
          <div class="token-item">
            <span class="token-label">过期时间:</span>
            <span>{{ tokenInfo.expiresAt }}</span>
          </div>
          
          <div class="token-notice">
            <p>请将此令牌安全地传达给用户，用户可以在重置密码页面使用此令牌重置密码。</p>
            <p>重置后的默认密码为：123456789</p>
          </div>
        </div>
      </div>
      
      <div class="no-token" v-else>
        <el-empty description="尚未生成令牌">
          <template #description>
            <p>请输入用户名并点击"生成重置令牌"按钮</p>
          </template>
        </el-empty>
      </div>
    </el-card>
    
    <el-card class="history-card">
      <template #header>
        <div class="history-header">
          <h3>最近生成的令牌</h3>
          <el-button type="primary" size="small" @click="fetchHistory">刷新</el-button>
        </div>
      </template>
      
      <el-table
        :data="tokenHistory"
        style="width: 100%"
        border
        v-loading="historyLoading"
      >
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="token" label="令牌" width="120" />
        <el-table-column prop="expiresAt" label="过期时间" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="copyToClipboard(scope.row.token)"
            >
              复制令牌
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'PasswordReset',
  setup() {
    const store = useStore()
    const resetFormRef = ref(null)
    const loading = ref(false)
    const historyLoading = ref(false)
    const tokenInfo = ref(null)
    const tokenHistory = ref([])
    
    const resetFormData = reactive({
      username: ''
    })
    
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ]
    }
    
    // 生成重置令牌
    const generateToken = async () => {
      if (!resetFormRef.value) return
      
      try {
        await resetFormRef.value.validate(async (valid) => {
          if (valid) {
            loading.value = true
            
            try {
              const response = await axios.post('/api/password/generate-reset-token', {
                username: resetFormData.username
              }, {
                headers: { Authorization: `Bearer ${store.state.token}` }
              })
              
              if (response.data.success) {
                tokenInfo.value = response.data.data
                ElMessage.success('令牌生成成功')
                
                // 刷新历史记录
                fetchHistory()
              } else {
                ElMessage.error(response.data.message || '令牌生成失败')
              }
            } catch (error) {
              ElMessage.error(error.response?.data?.message || '令牌生成失败，请稍后重试')
            } finally {
              loading.value = false
            }
          }
        })
      } catch (error) {
        ElMessage.error('操作异常，请稍后重试')
      }
    }
    
    // 获取历史记录
    // 注意：实际API可能需要实现这个接口，这里使用模拟数据
    const fetchHistory = async () => {
      historyLoading.value = true
      
      // 延时模拟API请求
      setTimeout(() => {
        if (tokenInfo.value) {
          // 模拟历史记录数据
          const existingIndex = tokenHistory.value.findIndex(item => item.username === tokenInfo.value.username)
          
          if (existingIndex >= 0) {
            tokenHistory.value[existingIndex] = tokenInfo.value
          } else {
            tokenHistory.value.unshift(tokenInfo.value)
          }
        }
        
        historyLoading.value = false
      }, 500)
    }
    
    // 复制到剪贴板
    const copyToClipboard = (text) => {
      navigator.clipboard.writeText(text).then(() => {
        ElMessage.success('已复制到剪贴板')
      }).catch(() => {
        ElMessage.error('复制失败，请手动复制')
      })
    }
    
    onMounted(() => {
      fetchHistory()
    })
    
    return {
      resetFormRef,
      resetFormData,
      rules,
      loading,
      historyLoading,
      tokenInfo,
      tokenHistory,
      generateToken,
      fetchHistory,
      copyToClipboard
    }
  }
}
</script>

<style scoped>
.password-reset {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 22px;
  color: #303133;
  margin-bottom: 5px;
}

.page-header p {
  color: #606266;
  font-size: 14px;
}

.reset-card {
  margin-bottom: 20px;
}

.reset-form {
  max-width: 500px;
}

.token-info {
  margin-top: 20px;
}

.token-details {
  margin-top: 20px;
  background-color: #f8f8f8;
  border-radius: 4px;
  padding: 15px;
}

.token-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.token-label {
  font-weight: bold;
  margin-right: 10px;
  min-width: 80px;
}

.token-notice {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #dcdfe6;
}

.token-notice p {
  color: #606266;
  margin-bottom: 5px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.history-header h3 {
  margin: 0;
  font-size: 16px;
}

.no-token {
  margin: 30px 0;
}
</style> 